﻿/********************************************************************
	日期:2022/4/29 22:51
	名称:CacheSvc
	邮箱:yunnibbd@163.com
	作者:yunni
	描述:缓存层
*********************************************************************/

using PEProtocol;
using System;
using System.Collections.Generic;
using System.Xml.XPath;

public class CacheSvc{
    private static CacheSvc instance = null;

    public static CacheSvc Instance{
        get{
            if (instance == null){
                instance = new CacheSvc();
            }

            return instance;
        }
    }

    private Dictionary<string, ServerSession> onLineAcctDic = new Dictionary<string, ServerSession>();
    private Dictionary<ServerSession, PlayerData> onLineSessionDic = new Dictionary<ServerSession, PlayerData>();
    private DBMgr dbMgr;

    public void Init(){
        dbMgr = DBMgr.Instance;
        PECommon.Log("CacheSvc Init Done");
    }

    public bool IsAcctOnLine(string acct){
        return onLineAcctDic.ContainsKey(acct);
    }

    /// <summary>
    /// 根据账号密码返回账户信息
    /// </summary>
    public PlayerData GetPlayerData(string acct, string pass){
        //TODO
        //从是数据库中查找
        return DBMgr.Instance.QueryPlayerData(acct, pass);
    }

    /// <summary>
    /// 账号上线，缓存数据
    /// </summary>
    public void AcctOnLine(string acct, ServerSession session, PlayerData playerData){
        onLineAcctDic.Add(acct, session);
        onLineSessionDic.Add(session, playerData);
    }

    public bool IsNameExists(string name){
        return dbMgr.QueryNameData(name);
    }

    public List<ServerSession> GetOnlineServerSessions(){
        List<ServerSession> lst = new List<ServerSession>();
        foreach (var item in onLineSessionDic){
            lst.Add(item.Key);
        }

        return lst;
    }

    public Dictionary<ServerSession, PlayerData> GetOnlineCache(){
        return onLineSessionDic;
    }

    public PlayerData GetPlayerDataBySession(ServerSession session){
        if (onLineSessionDic.TryGetValue(session, out PlayerData playerData)){
            return playerData;
        }

        return null;
    }

    public bool UpdatePlayerData(int id, PlayerData playerData){
        return dbMgr.UpdatePlayerData(id, playerData);
    }

    public void AcctOffine(ServerSession session){
        foreach (var item in onLineAcctDic){
            if (item.Value == session){
                onLineAcctDic.Remove(item.Key);
                break;
            }
        }

        bool success = onLineSessionDic.Remove(session);
        PECommon.Log("Offline Result:" + success + ", SessionID:" + session.sessionID);
    }

    public ServerSession GetOnlineServerSession(int ID){
        ServerSession session = null;
        foreach (KeyValuePair<ServerSession,PlayerData> data in onLineSessionDic){
            if (data.Value.id == ID){
                session = data.Key;
                break;
            }
        }

        return session;
    }
}
